import React, {
  useCallback, useEffect, useMemo
} from 'react'
import { View, Text } from '@tarojs/components'
import i18n from '@I18N'
import { LanguageType } from '@INTERFACES/Common'
import { PainLogITF } from '@INTERFACES/PainLog'
import EmptyLogs from '@COMPONENTS/DataCenter/EmptyLogs'
import { useSelector } from 'react-redux'
import dataCenterAction from '@ACTIONS/dataCenter'
import LogItem from '@COMPONENTS/DataCenter/LogItem'
import { useRequest } from '@HOOKS/useRequest'
import { PATIENT_SITE } from '@CONSTANTS/painLog'
import style from './PainLogSummary.module.scss'

interface Props {
  language: LanguageType
  dateBucket: string
  onEditLog: (item: PainLogITF) => void
  onDelete: (item: PainLogITF) => void
  onCreateLog: (site: PATIENT_SITE, isVisitorLogin?: boolean) => void
  onClickNoPain: (isVisitorLogin?: boolean) => void
}

const PainLogSummary: React.FC<Props> = (
  {
    language,
    dateBucket, onDelete,
    onEditLog,
    onCreateLog,
    onClickNoPain,
  }
) => {
  const { dispatchGetMyPainLogsByDateBucket } = dataCenterAction
  const isVisitor = useSelector(state => state.profile.isVisitor)
  const getMyPainLogsByDateBucket = useRequest(dispatchGetMyPainLogsByDateBucket)

  const { painLogPatient } = useSelector(state => state.patient)
  const pId = useMemo(() => (painLogPatient?.PatientId || painLogPatient?.p8Id), [painLogPatient])

  const painLogs = useSelector(state => state.dataCenter.painLogs)
  const getPainLogs = useCallback(
    () => {
      if (isVisitor) return
      getMyPainLogsByDateBucket(dateBucket)
    },
    [dateBucket, getMyPainLogsByDateBucket, isVisitor]
  )

  useEffect(() => {
    getPainLogs()
  }, [getPainLogs])
  const isHasPainLog = Array.isArray(painLogs) && painLogs.length > 0
  if (!isHasPainLog || !pId) {
    return (
      <EmptyLogs
        dateBucket={dateBucket}
        language={language}
        painLogPatient={painLogPatient}
        onCreateLog={onCreateLog}
        onClickNoPain={onClickNoPain}
      />
    )
  }
  const renderItem = (item: PainLogITF, index: number) => (
    <LogItem data={item} key={index} language={language} onDelete={onDelete} onEditLog={onEditLog} />
  )
  return (
    <View className={style.summary}>
      {painLogs?.map(renderItem)}
      <View className={style.buttonContainer}>
        <View className={`${style.btn} ${style.themeBtn}`} onClick={() => onCreateLog(PATIENT_SITE.Head)}>
          {`+ ${i18n.common.headache()}`}
        </View>
        <View className={style.btn} onClick={() => onCreateLog(PATIENT_SITE.Other)}>
          <Text>+ 其他部位痛</Text>
        </View>
      </View>
    </View>
  )
}

export default PainLogSummary
